<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class UserContacts extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->selectUserContacts($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    function POST($matches)
    {
        $req = RestUtils::processRequest('POST');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->insertUserContacts($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(201, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function selectUserContacts($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values))
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $query = "SELECT cd_contact,
                             ds_contact,
                             priority
                      FROM contacts
                      WHERE id_user = {$values['id_user']}";

            $result = @pg_query($db_handle, $query);
            if ($result) {
                $result = dbutils::dbresult_to_json($result);
            } else {
                $code = -1;
                $msg = 'no db records found ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);
        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }

    private function insertUserContacts($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('id_user', $values)
                || !array_key_exists('contacts', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            $id_user = $values['id_user'];

            $insert = "DELETE FROM contacts
                                    WHERE id_user={$id_user};";
            if ($values['contacts'])
            foreach ($values['contacts'] as $val) {
                if (!array_key_exists('cd_contact', $val)
                    || !array_key_exists('ds_contact', $val)
                    || !array_key_exists('priority', $val)
                )
                    return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

                $insert .= "INSERT INTO contacts (id_user,
                                             cd_contact,
                                             ds_contact,
                                             priority)
                                     VALUES ({$id_user},
                                             '{$val['cd_contact']}',
                                             '{$val['ds_contact']}',
                                             {$val['priority']});";
            }

            $db_handle = @pg_pconnect(dbutils::$conn_string);

            $result = @pg_query($db_handle, $insert);

            if (!$result) {
                $code = -1;
                $msg = 'inserting records not possible ' . @pg_last_error($db_handle);
            }

            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }
        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>
